package com.acmuno.greenchili;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class URLQuery {
	
	URL url;
	URLConnection uc;
	
	public URLQuery(){}
		
	public void addJSON(String lm){	

		try{
			uc = new URL("http://174.71.79.197:8080/linger/api/addMessage.php").openConnection();
			uc.setDoOutput(true);
			uc.connect();
			OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
			out.write(lm);
			out.flush();
			out.close();
			System.out.println("Message added to Linger Database!");
		}catch(MalformedURLException e){
			e.printStackTrace();
		}catch(IOException e){
			System.err.println("Cannot establish Output Stream for"  + uc + ".");
			e.printStackTrace();
		}catch(NullPointerException e){
			e.printStackTrace();
		}
	}
	
	public void listJSON(){
		
		StringBuilder sb = new StringBuilder();
		try {
			uc = new URL("http://174.71.79.197:8080/linger/api/listMessages.php").openConnection();
			uc.setDoInput(true);
			uc.connect();
			InputStreamReader in = new InputStreamReader(uc.getInputStream());
			while(in.read() != -1){
				sb.append(in.read());
			}
			in.close();			
			String message = sb.toString();			
			LingerMessage lm = new LingerMessage(message);
			System.out.println(lm.parseMessage());			
		}catch(MalformedURLException e){
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}catch(NullPointerException e){
			e.printStackTrace();
		}
	}	
}
